package com.dhms.vostok1.ui.main.select_mbr

import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import com.dhms.mine.R
import com.dhms.vostok1.base.BaseViewModel
import com.dhms.vostok1.base.BindingCommand
import com.dhms.vostok1.base.BindingConsumer
import com.dhms.vostok1.base.SingleLiveData
import com.dhms.vostok1.data.select_mbr.*
import com.dhms.vostok1.network.MoshiObject.moshi
import com.dhms.vostok1.service.net.NetworkApi
import com.dhms.vostok1.utils.ClickSpanUtil
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Types
import kotlinx.coroutines.flow.MutableStateFlow

class SelectMemberViewModel : BaseViewModel() {

    val backEvent = SingleLiveData<Boolean>()
    val dataList = SingleLiveData<MutableList<MultiItemInfo>>()
    val navText = MutableStateFlow<SpannableString?>(null)
    var navList = ArrayList<CompanyGroupBean>()
    var allIsChecked = MutableStateFlow(false)
    var allLayout = MutableStateFlow(false)
    val numString = MutableStateFlow(String.format(getString(R.string.select_num), 0))
    private val allGroupList = ArrayList<CompanyGroupBean>()
    val checkedList = ArrayList<MultiItemInfo>()
    val searchDataList = SingleLiveData<MutableList<MultiItemInfo>>()
    val searchViewVisible = MutableStateFlow(false)
    val searchKeyObservable = SingleLiveData<String>()
    val popEvent = SingleLiveData<Boolean>()
    val confirmEvent = SingleLiveData<String>()
    var organizationId = 0L

    init {
        getCompanyGroup()
    }

    val back = BindingCommand {//点击返回事件
        backEvent.value = true
    }

    val onTextChange = BindingConsumer<String> {
        searchKeyObservable.value = it
        searchViewVisible.value = it.isNotEmpty()
        searchMbr(it)
    }

    val cancelCommand = BindingCommand {
        searchViewVisible.value = false
        searchDataList.value?.clear()
    }

    val numClickCommand = BindingCommand {
        popEvent.value = true
    }

    val confirmCLickCommand = BindingCommand {
        if (checkedList.isEmpty()) {
            return@BindingCommand
        }
        val type = Types.newParameterizedType(List::class.java, Member::class.java)
        val jsonAdapter: JsonAdapter<List<Member>> = moshi.adapter(type)
        val list =
            checkedList.filter { it.mbr != null }.map { Member(it.mbr!!.us_id, it.mbr.us_name) }
        confirmEvent.value = jsonAdapter.toJson(list)

    }

    /**
     * 全部点击信息
     */
    val allClickCommand = BindingCommand {
        allIsChecked.value = !allIsChecked.value
        val list = ArrayList<MultiItemInfo>()
        dataList.value?.let { i ->
            list.addAll(i)
            list.filter { it.itemType == TYPE_MEMBER }
                .forEach { it.isChecked = allIsChecked.value }
            dataList.value = list
        }
    }

    /**
     * 获取部门人员信息
     */
    fun getMbrById(item: CompanyGroupBean) {
        onScope {
            val result = NetworkApi.getMember(item.id.toString())
            val data = result.getOrNull()?.body()?.data
            data?.let { i ->
                val list = ArrayList<MultiItemInfo>()
                allGroupList.filter { it.parent_id == item.id }
                    .forEach { list.add(MultiItemInfo(TYPE_GROUP, it, null, false)) }
                i.items.forEach { t ->
                    val li = checkedList.filter { it.mbr?.us_id == t.us_id }
                    list.add(MultiItemInfo(TYPE_MEMBER, null, t, li.isNotEmpty()))
                }
                allLayout.value = i.items.isNotEmpty()
                dataList.value = list
            }
            if (navList.contains(item)) {
                val list = navList.take(navList.indexOf(item) + 1)//截取列表
                navList.clear()
                navList.addAll(list)
            } else {
                navList.add(item)
            }
            navText.value = getText()
        }
    }

    /**
     * 获取公司层级
     */
    private fun getCompanyGroup() {
        onScope {
            val result = NetworkApi.getCompanyGroup()
            val data = result.getOrNull()?.body()?.data
            data?.let { l ->
                allGroupList.addAll(l)
                val index = l.indexOfFirst { it.id == organizationId }
                if (index >= 0) {
                    getMbrById(l[index])
                } else {
                    dataList.value = handelData(l)
                }
                navText.value = getText()
            }
        }
    }

    /**
     * 页面上部导航信息返回可点击
     */
    private fun getText(): SpannableString {
        var char = ""
        navList.forEach {
            if (navList.last() == it) {
                char += it.name
            } else {
                char = "$char${it.name} > "
            }
        }
        val span = SpannableString(char)
        navList.forEach {
            if (navList.last() == it) {
                span.setSpan(
                    ForegroundColorSpan(Color.parseColor("#999999")),
                    char.indexOf(it.name),
                    char.indexOf(it.name) + it.name.length,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            } else {
                ClickSpanUtil.setClickSpan(
                    span, char.indexOf(it.name),
                    char.indexOf(it.name) + it.name.length, Color.parseColor("#006CB8")
                ) {
                    if (navList.first() == it) {
                        allLayout.value = false
                        val index = allGroupList.indexOfFirst { it.id == organizationId }
                        if (index >= 0) {
                            getMbrById(allGroupList[index])
                        } else {
                            dataList.value = handelData(allGroupList)
                        }
                        navText.value = getText()
                    } else {
                        getMbrById(it)
                    }
                }
            }
        }
        return span
    }

    /**
     * 处理返回的公司层级信息
     * @param 公司层级列表
     */
    private fun handelData(l: List<CompanyGroupBean>): ArrayList<MultiItemInfo> {
        val list = ArrayList<MultiItemInfo>()
        navList.clear()
        navList.addAll(l.filter { it.id == organizationId })
        list.addAll(l.filter { it.parent_id == organizationId }
            .map { MultiItemInfo(TYPE_GROUP, it, null, false) })
        return list
    }

    /**
     * 选中或取消
     * @param item 选中的人员
     */
    fun changeCheckedList(item: MultiItemInfo) {
        if (item.isChecked) {
            val list = checkedList.filter { item.mbr?.us_id == it.mbr?.us_id }
            if (list.isEmpty()) {
                checkedList.add(item)
            }
        } else {
            checkedList.removeIf { it.mbr?.us_id == item.mbr?.us_id }
        }
        numString.value = String.format(getString(R.string.select_num), checkedList.size)
        val checkedList = dataList.value?.filter { it.itemType == TYPE_MEMBER && it.isChecked }
        val mbrList = dataList.value?.filter { it.itemType == TYPE_MEMBER }
        allIsChecked.value = checkedList?.size == mbrList?.size
    }

    /**
     * 搜索人员
     */

    private fun searchMbr(keyword: String) {
        if (keyword.isEmpty() || keyword.isBlank()) {
            return
        }
        onScope {
            //val bean = navList.last()
            //val result = NetworkApi.getMember(bean.id.toString(), view_sub_org = "false", keyword = keyword)
            //val data = result.getOrNull()?.body()?.data
            /* Log.d("tag",data.toString())
            val list = ArrayList<MultiItemInfo>()
            data?.items?.filter { it.us_name.contains(keyword) }?.forEach { t ->
                val items = checkedList.filter { it.mbr?.us_id == t.us_id }
                list.add(MultiItemInfo(TYPE_MEMBER, null, t, items.isNotEmpty()))
            }*/
            val list = ArrayList<MultiItemInfo>()
            val l=dataList.value?.filter { it.itemType== TYPE_MEMBER && it.mbr?.us_name?.contains(keyword)==true }
            l?.let {
               list.addAll(it)
            }
            searchDataList.value = list
        }
    }

    /**
     * 从h5页面接收的数据
     */
    fun default(str: String?) {
        str?.let {
            val type = Types.newParameterizedType(List::class.java, Member::class.java)
            val jsonAdapter: JsonAdapter<List<Member>> = moshi.adapter(type)
            val array = jsonAdapter.fromJson(str)
            array?.forEach {
                checkedList.add(
                    MultiItemInfo(
                        TYPE_MEMBER,
                        null,
                        Item(it.us_id, "", it.us_name, ""),
                        true
                    )
                )
            }
            numString.value = String.format(getString(R.string.select_num), checkedList.size)
        }
    }
}